package com.aop;

import com.service.BaseService;
import com.service.BuyService;
import com.utils.DBUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

public class JdkProxyTx {

    public void aop(){
        BaseService buyService = new BuyService();

        BaseService buyServiceProxy = (BaseService) Proxy.newProxyInstance(
                buyService.getClass().getClassLoader(),
                buyService.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args)  {
                        try{
                            Connection conn = DBUtils.getConn();
                            conn.setAutoCommit(false);//设置不自动提交
                            Object ret = method.invoke(buyService,args);
                            conn.commit();//提交
                            return ret;
                        }catch (Exception e){
                            try {
                                System.out.println("Jdk动态代理回滚事务....");
                                DBUtils.conn.rollback();
                            } catch (SQLException ex) {
                                throw new RuntimeException(ex);
                            }
                            throw new RuntimeException(e);
                        }finally {
                            DBUtils.close();
                        }

                    }
                }
        );

        buyServiceProxy.buy(200);

    }

}
